package system

import (
	"context"
	"gin-admin/global"
	"gin-admin/utils"
	"time"

	"github.com/mojocn/base64Captcha"
)

var ctx = context.Background()

type CaptchaService struct{}

var CaptchaServiceApp = &CaptchaService{}

/**
 * 获取验证码
 */
func (cs *CaptchaService) GetCaptcha() (string, string, error) {
	captcha := base64Captcha.NewCaptcha(base64Captcha.NewDriverDigit(80, 240, 6, 0.7, 80), base64Captcha.DefaultMemStore)
	id, b64s, answer, err := captcha.Generate()
	if err != nil {
		global.GA_LOGGER.Sugar().Errorw("获取验证码失败", "error", err)
		return "", "", err
	}
	redisUtils := &utils.RedisUtils{}
	redisUtils.Set(ctx, id, answer, global.GA_CONFIG.Redis.ExpiresAt*time.Second)
	return id, b64s, nil
}

/**
 * 验证验证码
 */
func (cs *CaptchaService) VerifyCaptcha(id, answer string) (bool, error) {
	if answer == global.GA_CONFIG.App.DefaultCaptcha {
		return true, nil
	}
	redisUtils := &utils.RedisUtils{}
	redisAnswer, err := redisUtils.Get(ctx, id)
	if err != nil {
		global.GA_LOGGER.Sugar().Errorw("redis获取验证码失败", "error", err)
		return false, err
	}
	if redisAnswer != answer {
		return false, nil
	}
	_ = redisUtils.Delete(ctx, id)
	return true, nil
}
